<template>
  <div class="shopbag">
    <div class="topnav">
      <van-nav-bar title="购物袋">
        <template #right>
          <div v-if="shopbagData.length > 0" @click="toggle">
            {{ flag ? "编辑" : "完成" }}
          </div>
        </template></van-nav-bar
      >
    </div>
    <div class="content">
      <div class="bgimg">
        <img class="navimg" src="../assets/images/nav.png" />
      </div>
      
      <div class="goods" v-for="item in shopbagData" :key="item.sid">
        <Good
          :goodData="item"
          @simpleSelect="getSimpleSelectStatus"
          @remove="removeOne(item.sid,item.count)"
        >
          <van-stepper
            v-model="item.count"
            theme="round"
            button-size="22"
            disable-input
            @change="changeCount(item)"
          />
        </Good>
      </div>
      <p class="lasttext" v-if="shopbagData.length > 0">
        哎呀，没有数据可以加载了
      </p>
    </div>

    <div class="zhifu" v-if="shopbagData.length > 0">
      <van-submit-bar
        v-show="flag"
        :price="total"
        button-text="提交订单"
        @submit="submit"
        button-color="rgb(12,52,186)"
      >
        <van-checkbox
          v-model="allCheck"
          @click="checkAll"
          checked-color="#0C34BA"
          >全选</van-checkbox
        >
      </van-submit-bar>
      <van-submit-bar
        v-show="!flag"
        button-text="删除选项"
        button-color="red"
        @submit="removeSelect"
      >
        <van-checkbox
          v-model="allCheck"
          @click="checkAll"
          checked-color="#0C34BA"
          
          >全选</van-checkbox
        >
      </van-submit-bar>
    </div>
    <div v-if="shopbagData.length === 0">
      <van-empty description="您还没有添加商品，赶快去逛一逛吧" />
    </div>
  </div>
</template>

<script>
import Good from "../components/Good";

export default {
  name: "Shopbag",
  data() {
    return {
      value: 1,
      flag: true,
      allCheck: false,
      shopbagData: [],
      total:0,
    };
  },
  components: {
    Good,
  },
  methods: {
    // 全选
    checkAll() {
      this.shopbagData.forEach((v) => {
        v.checked = this.allCheck;
      });
    },
    // 单选（从组件获取checked数据）
    getSimpleSelectStatus() {
      this.sum();
      for (let i = 0; i < this.shopbagData.length; i++) {
        if (!this.shopbagData[i].checked) {
          this.allCheck = false;
          return;
        }
      }
      this.allCheck = true;
    },
    // 修改编辑和完成状态
    toggle() {
      this.flag = !this.flag;
    },
    // 获取购物袋的数据
    getShopData() {
      let token = this.$cookies.get("TOKEN");

      this.axios({
        method: "GET",
        url: "/findAllShopcart",
        params: {
          tokenString: token,
        },
      })
        .then((res) => {
          if (res.data.code == 700) {
            //用户未登录, 拦截操作, 通知用户去登录
            this.$toast("请先登录");
            setTimeout(() => {
              this.$router.push({ name: "Login" });
            }, 2000);
            return;
          }
          if (res.data.code === 5000) {
            //添加一个单选状态属性
            res.data.result.forEach((v) => {
              v.checked = false;
            });
            this.shopbagData = res.data.result;
          }
        })
        .catch((err) => {
          
        });
    },
    // 修改数字
    changeCount(item) {
      let token = this.$cookies.get("TOKEN");

      this.axios({
        method: "POST",
        url: "/modifyShopcartCount",
        data: {
          tokenString: token,
          sid: item.sid,
          count: item.count,
        },
      })
        .then((res) => {
          if (res.data.code == 700) {
            //用户未登录, 拦截操作, 通知用户去登录
            this.$toast("请先登录");
            setTimeout(() => {
              this.$router.push({ name: "Login" });
            }, 2000);
            return;
            
          }
          if (res.data.code == 6000) {
            this.sum();

            let count = 0;
            this.shopbagData.forEach(v => {
              count += v.count;
            })
            
            this.$root.publicShopbagCount = count;
            
          }
        })
        .catch((err) => {
          
        });
    },
    // 删除商品
    deleteGood(sids,count) {
      let token = this.$cookies.get("TOKEN");

      this.axios({
        method: "POST",
        url: "/deleteShopcart",
        data: {
          tokenString: token,
          sids,
        },
      })
        .then((res) => {
          if (res.data.code == 700) {
            //用户未登录, 拦截操作, 通知用户去登录
            this.$toast("请先登录");
            setTimeout(() => {
              this.$router.push({ name: "Login" });
            }, 2000);
            return;
          }
          this.$toast(res.data.msg);
          if (res.data.code === 7000) {
            let sidsData = JSON.parse(sids);
            for (let i = 0; i < this.shopbagData.length; i++) {
              let sid = this.shopbagData[i].sid;
              if (sidsData.indexOf(sid) > -1) {
                this.shopbagData.splice(i, 1);
                i--;
              }
            }

            //需要重新判断是否全选
            this.getSimpleSelectStatus();

            this.sum();
            this.$root.publicShopbagCount -= count  ;
            if(this.$root.publicShopbagCount ===0){
              this.$root.publicShopbagCount = ""
            }
            
          }
        })
        .catch((err) => {
          
        });
    },
    // 删除单条
    removeOne(sid,count) {
      let sids = JSON.stringify([sid]);
      this.deleteGood(sids,count);
    },
    // 删除选中的商品
    removeSelect() {
      //获取勾选的商品
      let sids = [];
      let count = 0;
      this.shopbagData.forEach((v) => {
        if (v.checked) {
          sids.push(v.sid);
          count += v.count;
        }
      });

      if (sids.length === 0) {
        this.$toast("请选择删除的商品");
        return;
      }
      sids = JSON.stringify(sids);
      this.deleteGood(sids,count);
    },
    // 计算总金额
    sum(){
      let total = 0;
      this.shopbagData.forEach((v) => {
        if (v.checked) {
          total += v.count * v.price;
        }
      });
      this.total = total * 100;
    },
    // 提交订单
    submit(){
      let sids = [];
      this.shopbagData.forEach(v => {
        if (v.checked) {
          sids.push(v.sid);
        }
      })
      if(sids.length === 0){
          this.$toast("请购买商品")
          return
        }
      
      this.$router.push({name:'Order',query: {sids: sids.join('-')}})
    }
  },
  created() {
    this.getShopData();
  },
};
</script>

<style lang="less" scoped>
* {
  margin: 0;
  padding: 0;
}
/deep/ .van-empty {
  padding-top: 100px;
}
.shopbag {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgb(247, 247, 247);
  /deep/ .van-nav-bar__text {
    color: #000;
  }
  .lasttext {
    padding: 10px 0;
    display: block;
    text-align: center;
    color: gray;
    font-size: 14px;
  }
}
.bgimg{
  width: 100%;
  img{
    width: 100%;
  }
}
.content {
  position: fixed;
  top: 46px;
  bottom: 46px;
  left: 0;
  right: 0;
  overflow-y: auto;
}
.zhifu {
  /deep/ .van-submit-bar {
    bottom: 50px;
    padding-left: 15px;
    box-sizing: border-box;
  }
  /deep/ .van-submit-bar__price {
    color: rgb(12, 52, 186);
  }
  /deep/ .van-submit-bar__text {
    margin-right: 15px;
  }
  /deep/ .van-checkbox{
    margin-right: auto;
  }
}
</style>